#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>
#include <cstring>
#include <fcntl.h>
#include <sys/stat.h>

#define COMMAND_SIZE 1024   // 定义命令行输入的最大长度
#define FORMAT_FULL "[%s@%s %s]$ "    // 显示完整路径
#define FORMAT_SHORT "[%s@%s %s]$ "  // 显示最后一级目录

// 下面是shell定义全局数据
#define MAXARGC 128 // 定义命令行参数的最大个数
char* g_argv[MAXARGC];
int g_argc = 0;

// 环境变量表
#define MAX_ENVS 100
char* g_env[MAX_ENVS];
int g_envs = 0;

// 重定向关于的内容
#define NONE_REDIR 0
#define INPUT_REDIR 1
#define OUTPUT_REDIR 2
#define APPEND_REDIR 3

int redir = NONE_REDIR;
std::string filename;

// for test 
char cwd[1024];
char cwdenv[1024];

// last exit code 
int lastcode = 0;

const char* GetUserName()
{
    const char* name = getenv("USER");
    return name == NULL ? "None" : name;
}

const char* GetHostName()
{
    const char* hostname = getenv("HOSTNAME");
    return hostname == NULL ? "None" : hostname;
}

const char* GetPwd()
{
    //const char* pwd = getenv("PWD");
    const char* pwd = getcwd(cwd, sizeof(cwd));
    if(pwd != NULL)
    {
        snprintf(cwdenv, sizeof(cwdenv),"PWD=%s", cwd);
        putenv(cwdenv);     
    }
    return pwd == NULL ? "Nome" : pwd;
}

const char* GetHome()
{
    const char* home = getenv("HOME");
    return home == NULL ? "" : home;
}

bool Cd()
{
    // cd 
    if(g_argc == 1)
    {
        std::string home = GetHome();
        if(home.empty()) return true;
        chdir(home.c_str());
    }
    else 
    {
        std::string where = g_argv[1];
        // cd - / cd ~
        if (where == "-")
        {

        }
        else if (where == "~")
        {

        }
        else 
        {
            chdir(where.c_str());
        }
            
    }
    return true;
}

void Echo()
{
    if (g_argc == 2)
    {
        std::string opt = g_argv[1];
        if (opt == "$?")
        {
            std::cout << lastcode << std::endl;
            lastcode = 0;
        }
        else if (opt[0] == '$')
        {
            std::string env_name = opt.substr(1);
            const char* env_value = getenv(env_name.c_str());
            if(env_value)
                std::cout << env_value << std::endl;
        }
        else 
        {
            std::cout << opt << std::endl;
        }
    }
}

void InitEnv()
{
    extern char** environ;
    memset(g_env, 0, sizeof(g_env));
    g_envs = 0;

    for (int i = 0; environ[i]; ++i)
    {
        g_env[i] = (char*) malloc(strlen(environ[i] + 1));
        strcpy(g_env[i], environ[i]);
        g_envs++;
    }
    g_env[g_envs++] = "HAHA=for_test";
    g_env[g_envs] = NULL;

    // 2.导成环境变量
    for(int i = 0; g_env[i]; ++i)
    {
        putenv(g_env[i]);
    }
}

// / /a/b/c
std::string DirName(const char* pwd)
{
#define SLASH "/"
    std::string dir = pwd;
    if(dir == SLASH)  return SLASH;
    auto pos = dir.rfind(SLASH);
    if(pos == std::string::npos) return "BUG?";
    return dir.substr(pos+1);
#undef SLASH 
}

void MakeCommandLine(char CommandPrompt[], int size)
{
    snprintf(CommandPrompt, size, FORMAT_FULL, GetUserName(), GetHostName(), DirName(GetPwd()).c_str());
}

void PrintCommandPrompt()
{
    char prompt[COMMAND_SIZE];
    MakeCommandLine(prompt, sizeof(prompt));
    printf("%s", prompt);
    fflush(stdout);
}

bool GetCommandLine(char* out, int size)
{
    // ls -a -l => "ls -a -l\n" 字符串
    char* c = fgets(out, size, stdin);
    if (c == NULL) return false;
    out[strlen(out) - 1] = 0; // 清理\n
    if(strlen(out) == 0) return false;
    return true;
}

bool CommandParse(char* commandline)
{
#define SEP " "
    g_argc = 0;
    // 3.命令行分析 "ls -a -l" -> "ls" "-a" "-l"
    g_argv[g_argc++] = strtok(commandline, SEP);

    while((bool)(g_argv[g_argc++] = strtok(NULL, SEP)));
    g_argc--;
    
    return g_argc > 0 ? true : false;
#undef SEP 
}

void PrintArgv()
{
    for(int i = 0; g_argv[i]; ++i)
    {
        printf("arrgv[%d]->%s\n", i, g_argv[i]);
    }
    printf("%d\n", g_argc);
}

bool CheckAndExecBuiltin()
{
    std::string cmd = g_argv[0];
    if (cmd == "cd")
    {
        Cd();
        return true;
    }
    else if (cmd == "echo")
    {
        Echo();
        return true;
    }
    else if (cmd == "export")
    {

    }


    return false;
}
int Execute()
{ 
    // 判断是否为cd命令
    //if (g_argc > 0 && strcmp(g_argv[0], "cd") == 0) 
    //{ 
    //    const char* dir = (g_argc > 1) ? g_argv[1] : getenv("HOME");  // 若没传目录，默认切换到 HOME 目录

    //    // 调用 chdir 切换目录
    //    if (chdir(dir) != 0) 
    //        perror("cd failed");
    //    else 
    //    {
    //        // 切换成功后，更新环境变量 PWD（否则提示符不会显示新目录）
    //        char cwd[COMMAND_SIZE];
    //        if (getcwd(cwd, sizeof(cwd)) != NULL) // 获取当前实际目录
    //        {
    //            setenv("PWD", cwd, 1); // 第三个参数 1 表示覆盖原有 PWD
    //        }
    //    }
    //    return 0;
    //}
    pid_t id = fork();
    if(id == 0)
    {

        int fd = -1;
        // 子进程检测重定向情况
        if (redir == INPUT_REDIR)
        {
            fd = open(filename.c_str(), O_RDONLY);
            if (fd < 0) exit(1);
            dup2(fd, 0);
            close(fd);
        }
        else if (redir == OUTPUT_REDIR)
        {
            fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
            if (fd < 0) exit(2);
            dup2(fd, 1);
            close(fd);
        }
        else if (redir == APPEND_REDIR)
        {
            fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_APPEND, 0666);
            if (fd < 0) exit(2);
            dup2(fd, 1);
            close(fd);
        }
        else{}

        // 进程替换不影响重定向结果
        // child
        execvp(g_argv[0], g_argv);
        perror("execvp failed");
        exit(1);
    }
    
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid > 0)
    {
        lastcode = WEXITSTATUS(status);
    }
    return 0;
}

void TrimSpace(char commandline[], int &end)
{
    while(isspace(commandline[end]))
    {
        end++;
    }
}
void RdirCheck(char commandline[])
{
    redir = NONE_REDIR;
    filename.clear();
    int start = 0;
    int end = strlen(commandline) - 1;

    // "ls -a -l > file.txt" > >> <
    while(end > start)
    {
        if (commandline[end] == '<')
        {
            commandline[end++] = 0;
            TrimSpace(commandline, end);
            redir = INPUT_REDIR;
            filename = commandline + end;
            break;
        }
        else if (commandline[end] == '>')
        {
            if (commandline[end - 1] == '>')
            {
                // >>
                commandline[end - 1] = 0;
                redir = APPEND_REDIR;
            }
            else 
            {
                // >
                redir = OUTPUT_REDIR;
            }

            commandline[end++] = 0;
            TrimSpace(commandline, end);
            filename = commandline + end;
            break;
        }
        else 
        {
            end--;
        }
    }
}

int main()
{
    // shell启动时候,需要从系统中获取环境变量
    InitEnv();
    
    while(true)
    {

        // 1.输出命令行提示符
        PrintCommandPrompt();

        // 2.获取用户输入的命令
        char commandline[COMMAND_SIZE];
        if(!GetCommandLine(commandline, sizeof(commandline)))
            continue;
        

        // 3.重定向行分析 "ls -a -l > file.txt" -> "ls" "-a" "-l" "file.txt" -> 判定重定向方式
        RdirCheck(commandline);
        //printf("redir %d, filename %s\n", redir, filename.c_str());
        

        // 4.命令行分析 "ls -a -l" -> "ls" "-a" "-l"
        if(!CommandParse(commandline))
            continue;
        //PrintArgv();
        
        // 5.检测并处理是否为内键命令
       if(CheckAndExecBuiltin())
           continue;

        // 6.执行命令
        Execute();
    }
    
    // clear();
    return 0;
}
